<?php
/**
 * SyncEsService.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2021/1/17- 下午4:33
 */

namespace common\jobs\services;


use common\jobs\models\ComProducts;
use common\jobs\models\PddCopyProducts;
use common\jobs\models\PddMallProduct;
use common\models\es\EsComProducts;
use common\models\es\EsCopyProducts;
use common\models\es\EsPddMallProducts;
use yii\helpers\FileHelper;
use Yii;
class SyncEsService
{

    /**
     * 同步tb_mall_product表到es
     * @param $id
     * @return bool
     * @throws \yii\base\Exception
     */
    public function syncMallProduct($id)
    {
        if (!$id) {
            return false;
        }
        $insert = $update = $error = 0;
        $id = is_array($id) ? $id : [$id];
        $products = [];
        $models = PddMallProduct::find()->where(['goods_id' => $id])->all();
        $es = new EsPddMallProducts();
        $attributes = $es->attributes();
        foreach ($models as $model) {
            $product = [];
            foreach ($attributes as $column) {
                $product[$column] = $model->$column;
            }
            $products[] = $product;
        }
        $res = $products ? $es->syncData($products) : [];
        if (isset($res['errors']) && $res['errors'] == false) {
            return true;
        }
        if(isset($res['items']) && is_array($res['items']))
        {
            foreach($res['items'] as $k => $item)
            {
                if (!in_array($item['index']['status'], [200, 201])) {
                    $error++;
                    $errMsg = isset($item['index']['error']) ? '[pdd_mall_product]主键id:' . $item['index']['_id'] . ',' . json_encode($item['index']['error'],JSON_UNESCAPED_UNICODE) : '[tb_mall_product]主键id:' . $item['index']['_id'];
                    $this->_writeSyncLog($errMsg);
                    continue;
                }
                if (isset($item['index']['result']) && $item['index']['result'] == 'updated') {
                    $update++;
                } else {
                    $insert++;
                }
            }
        }
        return false;
    }

    /**
     * 同步com_products数据到es
     * @param array|int $id
     * @return bool
     * @throws \yii\base\Exception
     */
    public function syncCloudProduct($id)
    {
        if (!$id) {
            return false;
        }
        $insert = $update = $error = 0;
        $id = is_array($id) ? $id : [$id];
        $products = [];
        $models = ComProducts::find()->where(['id' => $id])->all();
        $es = new EsComProducts();
        $attributes = $es->attributes();
        foreach ($models as $model) {
            $product = [];
            foreach ($attributes as $column) {
                $product[$column] = $model->$column;
            }
            $products[] = $product;
        }
        $res = $products ? $es->syncData($products) : [];
        if (isset($res['errors']) && $res['errors'] == false) {
            return true;
        }
        if(isset($res['items']) && is_array($res['items']))
        {
            foreach($res['items'] as $k => $item)
            {
                if (!in_array($item['index']['status'], [200, 201])) {
                    $error++;
                    $errMsg = isset($item['index']['error']) ? '[com_products]主键id:' . $item['index']['_id'] . ',' . json_encode($item['index']['error'],JSON_UNESCAPED_UNICODE) : '[com_products]主键id:' . $item['index']['_id'];
                    $this->_writeSyncLog($errMsg);
                    continue;
                }
                if (isset($item['index']['result']) && $item['index']['result'] == 'updated') {
                    $update++;
                } else {
                    $insert++;
                }
            }
        }
        return false;
    }

    /**
     * 同步tb_copy_products数据到es
     * @param $id
     * @return bool
     * @throws \yii\base\Exception
     */
    public function syncCopyProducts($id)
    {
        if (!$id) {
            return false;
        }
        $insert = $update = $error = 0;
        $id = is_array($id) ? $id : [$id];
        $products = [];
        $models = PddCopyProducts::find()->where(['id' => $id])->all();
        $es = new EsCopyProducts();
        $attributes = $es->attributes();
        foreach ($models as $model) {
            $product = [];
            foreach ($attributes as $column) {
                $product[$column] = $model->$column;
            }
            $products[] = $product;
        }
        $res = $products ? $es->syncData($products) : [];
        if (isset($res['errors']) && $res['errors'] == false) {
            return true;
        }
        if(isset($res['items']) && is_array($res['items']))
        {
            foreach($res['items'] as $k => $item)
            {
                if (!in_array($item['index']['status'], [200, 201])) {
                    $error++;
                    $errMsg = isset($item['index']['error']) ? '[tb_copy_products]id:' . $item['index']['_id'] . ',' . json_encode($item['index']['error'],JSON_UNESCAPED_UNICODE) : '未知错误,[tb_copy_products]id:' . $item['index']['_id'];
                    $this->_writeSyncLog($errMsg);
                    continue;
                }
                if (isset($item['index']['result']) && $item['index']['result'] == 'updated') {
                    $update++;
                } else {
                    $insert++;
                }
            }
        }
        return false;
    }


    /**
     * 同步es日志记录
     * @param $msg
     * @throws \yii\base\Exception
     */
    private function _writeSyncLog($msg)
    {

        $path = Yii::getAlias('@runtime/sync/es/');

        //目录如果不存就先创建目录
        if(!is_dir($path)) {
            FileHelper::createDirectory($path);
        }

        $cp = fopen($path.'log-'.date('Ymd').'.log', "a+");
        $txt = "【".date('Y-m-d H:i:s',time())."】---".$msg."\r\n";
        fwrite($cp, $txt);
        fclose($cp);
    }
}